package com.wl.api.controller.base;

import com.alibaba.fastjson.JSON;
import com.wl.api.common.utils.ErrorCodeEnum;
import com.wl.api.common.utils.RWYException;
import com.wl.api.common.utils.WebUtil;
import com.wl.api.filter.autentication.AuthorizeStatus;
import lombok.extern.log4j.Log4j;
import org.apache.log4j.spi.ErrorCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@ControllerAdvice
@Log4j
public class GlobalExceptionHandler {
	 
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public void jsonErrorHandler(HttpServletRequest req,HttpServletResponse response, Exception e) throws Exception {
	log.error("url:" +req.getRequestURI() + " req param:" +  WebUtil.getParameters(req).toString());
	log.error(responseStack(e.getStackTrace()));
	log.error(e.getMessage());
	response.setCharacterEncoding("UTF-8");
	response.setContentType("application/json; charset=utf-8");
	 PrintWriter writer= response.getWriter();
	 String errorCode = "",  msg = "";
	 int status = 400;
	 if (e instanceof RWYException.AuthorizeException) {
		 status = 401;
		 errorCode = ErrorCodeEnum.sc_unauthorized.getError_code();
		 msg = ErrorCodeEnum.sc_unauthorized.getMessage();
	  } else if(e instanceof  RWYException.ForbiddenException) {
	 	status = 403;
	 	errorCode = ErrorCodeEnum.sc_forbidden.getError_code();
	 	msg = ErrorCodeEnum.sc_forbidden.getMessage();
	 } else if (e instanceof  RWYException.ErrorException) {
	 	status = 400;
	 	errorCode = ErrorCodeEnum.bad_request.getError_code();
	 	msg = ErrorCodeEnum.bad_request.getMessage();
	 } else {
	  	status = 400;
		 errorCode = ErrorCodeEnum.bad_request.getError_code();
		 msg = ErrorCodeEnum.bad_request.getMessage();
	 }
	 response.setStatus(status);
	 writer.write(JSON.toJSONString(respMes(errorCode, msg, req.getRequestURI())));
	 writer.flush();
	 writer.close();
	}
	
	private AuthorizeStatus respMes(String status, String message, String requestUrl) {
		return  AuthorizeStatus.builder().errorCode(status).msg(message).request(requestUrl).build();
	}

	private String responseStack(StackTraceElement[] stack) {
		StringBuffer sb = new StringBuffer();
		if (stack != null) {
			for(int i =0 ; i < stack.length ; i++) {
				sb.append(stack[i].toString()+"; ");
			}
		}
		return sb.toString();
	}
}
